package com.itheima.controller;

import com.itheima.common.Result;
import com.itheima.pojo.LoginDto;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import com.itheima.utils.SendSms;
import com.itheima.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Random;

@RestController
public class UserController {
    @Autowired
    private HttpServletRequest request;
    //登录发送验证码
@PostMapping("/validateCode/send4Login.do")
    public Result senMsg(LoginDto loginDto){
    Random random=new Random();
    int code = random.nextInt(1000000);
    HttpSession session = request.getSession();
   // SendSms.sendMsg(loginDto.getTelephone(),code+"");
    session.setAttribute(loginDto.getTelephone(),code+"");
    System.out.println(code);
    return new Result(true,"发送验证码成功");
}
@Autowired
private MemberService memberService;
@PostMapping("/member/login.do")
    public Result login(@RequestBody LoginDto loginDto){
    System.out.println(loginDto+"-------------");
    if(loginDto==null){
        return new  Result(false,"数据输入有误");
    }
    //获得储存在session中的验证码
    HttpSession session = request.getSession();
    String  code = (String) session.getAttribute(loginDto.getTelephone());
    if(!code.equals(loginDto.getValidateCode())){
        return new  Result(false,"验证码输入有误");
    }
    //根据电话号码查询是否该用户已经注册，如果没有则注册
     Member member= memberService.seletMember(loginDto);
    if(member==null){
        memberService.addMember(loginDto);
        session.setAttribute("telephoe",loginDto.getTelephone());
        return new Result(true,"登录成功");
    }
    session.setAttribute("telephoe",loginDto.getTelephone());
    return new Result(true,"登录成功");
}

//预约发送验证码
    @PostMapping("/validateCode/send4Order.do")
    public Result senMsgOrder(LoginDto loginDto){
        String code = ValidateCodeUtils.generateValidateCode4String(6);
        HttpSession session = request.getSession();
        // SendSms.sendMsg(loginDto.getTelephone(),code+"");
        session.setAttribute(loginDto.getTelephone(),code);
        System.out.println(code);
        return new Result(true,"发送验证码成功");
    }


}
